import { uploadApi } from '@/api/upload'
import { ACCESS_TOKEN, TENANTID } from '@/store/mutation-types'
import Vue from 'vue'
import { getFilename } from '@/utils/common'

export const props = {
  // 绑定图片 limit === 1 ? url : [url]
  value: {
    type: [String, Array],
    default: ''
  },
  // 是否禁用
  disabled: {
    type: Boolean,
    default: false
  },
  // 限制上传数量 设置为0则不限制上传数量
  limit: {
    type: Number,
    default: 1
  },
  // 图片大小限制 M
  fileSize: {
    type: Number,
    default: 10
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true
  },
  // 图片宽度
  width: {
    type: Number,
    default: 104
  },
  // 图片高度
  height: {
    type: Number,
    default: 104
  },
  // 圆角
  borderRadius: {
    type: String,
    default: ''
  },
  // 是否取素材库
  warehouse: {
    type: Boolean,
    default: false
  }
}

export const watch = {
  value: {
    handler(val) {
      if (val) {
        // 首先将值转为数组
        const list = Array.isArray(val) ? val : [val]
        // 然后将数组转为对象数组
        const urlList = this.fileList.filter(v => v.status === 'done').map(v => v.thumbUrl || v.url)
        if (JSON.stringify(list) === JSON.stringify(urlList)) return

        this.fileList = list.map((url,i) => {
          return {
            uid: Date.parse(new Date()) + i,
            name: getFilename(url),
            thumbUrl: url,
            status: 'done'
          }
        })
        this.upDom()
      } else {
        this.fileList = []
        return []
      }
    },
    deep: true,
    immediate: true
  }
  // width() {
  //   this.upDom()
  // },
  // height() {
  //   this.upDom()
  // },
  // borderRadius() {
  //   this.upDom()
  // }
}

export const computed = {
  // 是否显示提示
  showTip() {
    return this.isShowTip && (this.fileType || this.fileSize)
  },
  tipText() {
    if (!this.showTip) {
      return ''
    } else {
      let text = `<p class="fz-12">请上传`
      if (this.fileSize) {
        text += `大小不超过 <b style="color: #ff7875">${this.fileSize}MB</b>`
      }
      if (this.fileType) {
        text += `格式为 <b style="color: #ff7875">${this.fileType.join(' ')}</b> `
      }
      text += this.fileSource === 'video' ? '视频</p>' : '图片</p>'
      return text
    }
  }
}

export const data = {
  dynamicID: '',
  uploadApi,
  headers: {
    token: Vue.ls.get(ACCESS_TOKEN),
    tenantId: Vue.ls.get(TENANTID)
  },
  fileList: []
}

export const methods = {
  // 上传图片之前
  beforeUpload(file) {
    const that = this
    const upfileScope = that.fileType.map(v => `${that.fileSource}/` + v.replace('.', ''))
    const isImgType = upfileScope.includes(file.type)
    if (!isImgType) {
      that.$message.error(`请上传${that.fileType.join(' ')}格式的${that.fileSource === 'video' ? '视频' : '图片'}!`)
    }
    const isImgSize = file.size / 1024 / 1024 < that.fileSize
    if (!isImgSize) {
      that.$message.error(`${that.fileSource === 'video' ? '视频' : '图片'}大小不能超过${that.fileSize}M!`)
    }

    // 需要裁剪-拦截上传
    const isCropper = !that.cropper
    if (!isCropper) {
      that.$refs.ImgCropper.show()

      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => {
        that.$nextTick(() => {
          that.$refs.ImgCropper.options.img = reader.result
        })
      }
    }

    if (!isImgType || !isImgSize || !isCropper) {
      that.$nextTick(() => {
        // 删除列表中被拦截文件
        that.upDom()
        that.fileList = that.fileList.filter(v => v.uid !== file.uid)
      })
    }
    return isImgType && isImgSize && isCropper
  },
  // 文件列表变化
  handleChange({ file, fileList, event }) {
    const that = this;

    if(that.limit && fileList.length > that.limit){
      that.$message.warning({
        content: `最多上传${that.limit}${that.fileSource === 'video' ? '个视频' : '张图片'},本次选择已超出,已自动去除超出文件。`,
        key: 'upMaxLength'
      })
    }

    that.fileList = that.limit ? fileList.splice(0, that.limit) : fileList;
    if (file.status === 'done') {
      // 上传完成
      that.fileList.forEach(v => {
        if (v.response) {
          const { code, data } = v.response
          if (code === 0 && data && data.fileUrl) {
            v.thumbUrl = data.fileUrl // 更新视图,替换为在线链接

            if(that.fileSource === 'video'){ // 重载视频,不然显示不出来
              const currentVideo = document.getElementById(v.uid);
              currentVideo.src = data.fileUrl;
              currentVideo.load();
            }
          }
        }
      })
      that.upVmodel() // 更新v-model
    } else if (file.status === 'removed') {
      // 删除
      that.upVmodel() // 更新v-model
    }else{
      that.upDom()
    }
  },
  // 在线路径追加进已上传列表
  urlPushFileList(urlList) {
    urlList.forEach((url,i) => {
      this.fileList.push({
        uid: Date.parse(new Date()) + i,
        name: getFilename(url),
        thumbUrl: url,
        status: 'done'
      })
    })
  },
  // 更新父组件v-model
  upVmodel() {
    const successList = this.fileList.filter(v => v.status === 'done')
    const urlList = successList.map(v => v.thumbUrl)

    if(this.limit !== 1 || Array.isArray(this.value)){
      this.$emit('input', urlList);
    }else{
      this.$emit('input', urlList.length ? urlList[urlList.length - 1] : '');
    }
    this.$emit('change', successList) // 需要使用file文件等场景
    this.upDom()
  },
  // 展示样式根据宽高比例调整
  upDom() {
    const that = this
    that.dynamicID = `width-${that.width}_height-${that.height}`
    if (that.width === 104 && that.height === 104 && !that.borderRadius) return
    setTimeout(() => {
      const parent = document.querySelectorAll(`#${that.dynamicID}`)
      Array.prototype.forEach.call(parent, function(parentNode) {
        const elements1 = parentNode.querySelectorAll('.ant-upload-list-item-list-type-picture-card')
        const elements2 = parentNode.querySelectorAll('.ant-upload-list-picture-card-container')
        const elements3 = parentNode.querySelectorAll('.ant-upload-select-picture-card')
        const elements4 = parentNode.querySelectorAll('.ant-upload-list-item-uploading-text')
        Array.prototype.forEach.call([...elements1, ...elements2, ...elements3, ...elements4], function(element) {
          element.style.width = `${that.width}px`
          element.style.height = `${that.height}px`
          element.style.borderRadius = that.borderRadius
        })
      })
    }, 100)
  }
}

export const getBase64 = file => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}
